<?php
    require_once './vendor/autoload.php';
    use EasyWeChat\Factory;
    include_once './config.php';
    $config = [
        'app_id' => $APP_ID,
        'secret' => $SECRET,
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',
        'oauth' => [
          'scopes'   => ['snsapi_userinfo'],
          'callback' => './openid.php',
       ],
    ];
    $app = Factory::officialAccount($config);
    $oauth = $app->oauth;
    if(isset($_GET['state']) && $_GET['state']){ //授权登录回调
        $user = $oauth->user();
        $wechat_user = $user->toArray();
        $_SESSION['wechat_user'] = $wechat_user;
        if($_COOKIE['user']){ //如果用户已登录
            $user = json_decode($_COOKIE['user'],true);
            $openid = $wechat_user['original']['openid'];
            $query = "update whw_user set nickname = '',avatar = '',openid = '' where openid = ".quote($openid);
            $objDBCD14->execute($query);
            $query = "update whw_user set nickname = ".quote($wechat_user['nickname']).",avatar = ".quote($wechat_user['avatar']).",openid = ".quote($openid)." where id=".getInt($user['id']);
            $objDBCD14->execute($query);
        } else {
            $query = "select * from whw_user where openid=".quote($openid);
            $user = $objDBCD14->queryUniqueObject($query);
            if($user){
                $expire=time()+60*60*24*30;
                setcookie("user", json_encode($user), $expire);
            } else {
                header("location:login.php");
                exit;
            }
        }
        if($user['type'] == 1){
            header("location:index.php");
        } else {
            header("location:worker.php");
        }
    } else {
        // 未登录
        if (empty($_SESSION['wechat_user'])) {
           $oauth->redirect()->send();
        } else {
           header("location:login.php");
        }
    }
    
?>